import { getPatrolTaskById } from '@/api'
import { realRoute } from '@/business/realRoute'
import { useChangeCar } from '@/composables/useChangeCar'
import { ElMessage } from '@/stores/elMessage'
import { useSwitchComponents } from '@/stores/switchComponents'
import type { CarInfo } from '@/types'
import { i18n, initWebSocket } from '@/utils'
import { Map, Marker, VectorLayer } from 'maptalks'
import { ref } from 'vue'
import { map } from '../shared/map/base'
import { useRecordStore } from '../shared/map/record'
import { handleConfirmPatrolTaskPath, taskPathLayer, taskpathPoints } from '../shared/map/taskPath'
import { hasCoordinate, isTheSameCar } from './common'
const carMarkerLayer: VectorLayer = new VectorLayer('marker')
const smallCarMarkerLayer: VectorLayer = new VectorLayer('marker-small')
let ws: WebSocket | undefined
export const isConnectedWS = ref(false)
function initCarMarkerLayer(map: Map, type: number) {
  if (type === 0) {
    carMarkerLayer.addTo(map)
  } else if (type === 1) {
    smallCarMarkerLayer.addTo(map)
  }
}

function tryCloseWS() {
  if (ws) {
    ws.close()
  }
}

//是否显示结束跑圈按钮
export const isRainTask = ref<boolean>(false)

export const latitude = ref<number>(0)
export const longitude = ref<number>(0)

export function initMarker(data: CarInfo) {
  latitude.value = data.latitude
  longitude.value = data.longitude
  const ChangeCar = useChangeCar()
  carMarkerLayer.clear()
  smallCarMarkerLayer.clear()
  if (hasCoordinate(data) && isTheSameCar(data)) {
    const point = new Marker([data.longitude, data.latitude], {
      symbol: {
        markerType: 'triangle',
        markerFill: 'red',
        markerWidth: 14,
        markerHeight: 16,
        markerRotation: -Number(data.heading)
      }
    })
    const point1 = new Marker([data.longitude, data.latitude], {
      symbol: {
        markerType: 'triangle',
        markerFill: 'red',
        markerWidth: 14,
        markerHeight: 16,
        markerRotation: -Number(data.heading)
      }
    })
    if (carMarkerLayer) {
      carMarkerLayer.addGeometry(point)
    }
    if (smallCarMarkerLayer) {
      smallCarMarkerLayer.addGeometry(point1)
    }

    const switchComponents = useSwitchComponents()
    if (switchComponents.showComponent === true) {
      point.setMenuItems([
        {
          item: i18n.global.t('xuan-ze-xie-tong-che-liang'),
          click: () => {
            ChangeCar.carDialogVisible = true
          }
        }
      ])
    }
  }
}

function updateMarker(e: MessageEvent<any>) {
  if (e.data !== 'heartbeat') {
    const data: CarInfo = JSON.parse(e.data)
    if (!data.taskStatus) {
      initMarker(data)
    }

    const record = useRecordStore()
    if (record.isRecord) record.initRecordPath(data)
    if (data.taskStatus === 'start') onTaskStatusStart(data.taskID!)

    if (data.taskStatus === 'end') onTaskStatusEnd()
    realRoute.newPoint(data)
  }
}

//任务id
export const taskId = ref<number | null>(null)

async function onTaskStatusStart(taskID: number) {
  realRoute.openMode(map)
  clearTaskPathLayer()
  ElMessage({ type: 'success', message: i18n.global.t('kai-shi-zhi-hang-ren-wu') })
  const res: any = await getPatrolTaskById(taskID)
  taskId.value = taskID
  if (res.data.type === 2) {
    isRainTask.value = true
  } else {
    isRainTask.value = false
  }
  const route = res.data?.route || []
  handleConfirmPatrolTaskPath(route)
}

function onTaskStatusEnd() {
  realRoute.closeMode()
  clearTaskPathLayer()
  ElMessage({ type: 'success', message: i18n.global.t('ren-wu-zhi-hang-jie-shu') })
  isRainTask.value = false
}

function clearTaskPathLayer() {
  taskPathLayer.clear()
  taskpathPoints.length = 0
}

// async function initCar() {
//   carMarkerLayer.clear()
//   const { data } = await getCarLog()
//   const carList: CarInfo[] = data?.list || []
//   for (const data of carList) {
//     if (data.longitude && data.latitude) {
//       const point = new Marker([data.longitude, data.latitude], {
//         symbol: {
//           markerType: 'triangle',
//           markerFill: 'yellow',
//           markerWidth: 14,
//           markerHeight: 16,
//           markerRotation: -Number(data.heading)
//         }
//       })

//       carMarkerLayer.addGeometry(point)
//     }
//   }
// }

export async function addMarker(data: any) {
  const record = useRecordStore()
  record.closeIsRecord()
  realRoute.closeMode()
  clearTaskPathLayer()
  record.recordPathLayer.clear()
  initMarker(data)
}

export function initMakerLayer(map: Map, type: number) {
  initCarMarkerLayer(map, type)
}

export function onCarPoisition() {
  tryCloseWS()
  ws = initWebSocket('/websocket/patroling/location', {
    onmessage: updateMarker,
    onopen: onOpen,
    onclose: onClose,
    onerror: onError
  })
}

function onOpen() {
  isConnectedWS.value = true
  ElMessage({
    type: 'success',
    message: i18n.global.t('jian-ting-wei-zhi-lian-jie-cheng-gong')
  })
}

function onClose() {
  isConnectedWS.value = false
  ElMessage({
    type: 'warning',
    message: i18n.global.t('jian-ting-wei-zhi-lian-jie-duan-kai')
  })
}

function onError() {
  isConnectedWS.value = false
  ElMessage({
    type: 'error',
    message: i18n.global.t('jian-ting-wei-zhi-lian-jie-cuo-wu')
  })
}
